package com.glkj.vipsystem.modules.merchant.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.enums.StockApplyFormType;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.common.utils.Query;
import com.glkj.vipsystem.common.utils.R;
import com.glkj.vipsystem.entity.ao.GoodsAO;
import com.glkj.vipsystem.entity.gen.StockApplyForm;
import com.glkj.vipsystem.modules.sys.controller.AbstractController;
import com.glkj.vipsystem.service.IGoodsService;
import com.glkj.vipsystem.service.IStockApplyFormService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 出入、移库单控制器
 *
 * @author LiMuchan
 */
@RestController
@RequestMapping("/merchant/shop/stock/applyForm")
public class StockApplyFormController extends AbstractController {

    @Resource
    private IStockApplyFormService stockApplyFormService;
    @Resource
    private IGoodsService goodsService;

    /**
     * 列表
     */
    @GetMapping(value = "/list")
    @RequiresPermissions({"merchant:shop:stock"})
    public R list(@RequestParam Map<String, Object> params) {
        String outShopName = (String) params.get("outShopName");
        String inShopName = (String) params.get("inShopName");
        String time = (String) params.get("time");
        String type = (String) params.get("type");
        String status = (String) params.get("status");

        Wrapper<StockApplyForm> wrapper = new EntityWrapper<>();
        wrapper.orderBy("status asc,id desc");
        wrapper.setSqlSelect("*,(select shop_name from t_shop where id = t_stock_apply_form.in_shop_id) as inShopName" +
                ",(select shop_name from t_shop where id = t_stock_apply_form.out_shop_id) as outShopName" +
                ",(select username from sys_user where user_id = t_stock_apply_form.action_user_id) as actionUsername" +
                ",(select username from sys_user where user_id = t_stock_apply_form.verify_user_id) as verifyUsername");

        if (StringUtils.isNotBlank(outShopName)) {
            wrapper.where("out_shop_id in (select id from t_shop where shop_name like '%" + outShopName + "%')");
        }
        if (StringUtils.isNotBlank(inShopName)) {
            wrapper.where("in_shop_id in (select id from t_shop where shop_name like '%" + inShopName + "%')");
        }

        String username = getUser().getUsername();
        // 权限判断
        if (isCompanyRole()){
            wrapper.where("company_id = (select id from t_company where `username` = '" + username + "')");
        } else if (isEmployeeRole()){
            // 店铺管理员 出货或入货店铺是就能看
            wrapper.where("(in_shop_id = (select shop_id from t_employee where `username` = '"+ username +"')" +
                    " or out_shop_id = (select shop_id from t_employee where `username` = '"+ username +"'))");
        }

        if (StringUtils.isNotBlank(time) && time.contains("~")) {
            String[] times = time.split("~");
            wrapper.ge("verify_time", times[0].trim());
            wrapper.le("verify_time", times[1].trim() + " 23:59:59");
        }
        if (StringUtils.isNotBlank(type)) {
            wrapper.eq("type", type);
        }
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("status", status);
        }

        Page<StockApplyForm> page = stockApplyFormService.selectPage(
                new Query<StockApplyForm>(params).getPage(),
                wrapper
        );
        return R.ok().put("page", new PageUtils(page));
    }

    /**
     * 出入、移库单商品列表
     */
    @GetMapping(value = "/goods-list/{formId}")
    @RequiresPermissions({"merchant:shop:stock"})
    public R goodsList(@PathVariable("formId") Integer formId) {
        if (formId == null) {
            return R.error("formId空");
        }
        StockApplyForm stockApplyForm = this.stockApplyFormService.selectById(formId);
        if (stockApplyForm == null) {
            return R.error("出入、移库单不存在");
        }
        if (stockApplyForm.getType() == StockApplyFormType.Yiku.getType()) {
            List<GoodsAO> goodsAOS = goodsService.selectList(
                    new EntityWrapper<GoodsAO>()
                            .setSqlSelect("*" +
                                    ",(select cat_name from t_goods_cat where id = t_goods.cat_id) as catName" +
                                    ",(select num from t_stock_apply_form_goods where goods_id = t_goods.id and stock_apply_form_id = " + formId + ") as num")
                            .where("id in (select goods_id from t_stock_apply_form_goods where stock_apply_form_id = " + formId + ")")
            );
            return R.ok().put("data", goodsAOS);
        } else {
            List<GoodsAO> goodsAOS = goodsService.selectList(
                    new EntityWrapper<GoodsAO>()
                            .setSqlSelect("*" +
                                    ",(select cat_name from t_goods_cat where id = t_goods.cat_id) as catName" +
                                    ",(select num from t_stock_record where goods_id = t_goods.id and form_id = " + formId + ") as num")
                            .where("id in (select goods_id from t_stock_record where form_id = " + formId + ")")
            );
            return R.ok().put("data", goodsAOS);
        }
    }

    /**
     * 详情
     */
    @GetMapping(value = "/detail/{id}")
    @RequiresPermissions({"merchant:shop:stock"})
    public R detail(@PathVariable("id") Integer id) {
        return R.ok().put("item", stockApplyFormService.selectById(id));
    }

    /**
     * 保存新增
     */
    @PostMapping(value = "/save")
    @RequiresPermissions({"merchant:shop:stock"})
    public R save(@RequestBody StockApplyForm stockApplyForm) {
        stockApplyFormService.save(stockApplyForm, getUserId());
        return R.ok();
    }


    /**
     * 审核
     */
    @PostMapping(value = "/audit")
    @RequiresPermissions({"merchant:shop:stock"})
    public R update(@RequestBody StockApplyForm stockApplyForm) {
        if (stockApplyForm.getStatus() != 2 && stockApplyForm.getStatus() != 3) {
            return R.error("状态错误");
        }
        stockApplyFormService.audit(stockApplyForm, getUserId());
        return R.ok();
    }

    /**
     * 获取库存记录类型
     */
    @GetMapping(value = "/type")
    @RequiresPermissions({"merchant:shop:stock"})
    public R type() {
        List<JSONObject> data = new ArrayList<>();
        StockApplyFormType[] values = StockApplyFormType.values();

        for (StockApplyFormType value : values) {
            JSONObject type = new JSONObject();
            type.put("label", value.getMsg());
            type.put("value", value.getType());
            data.add(type);
        }
        return R.ok().put("data", data);
    }
}
